from docxtpl import DocxTemplate
import pandas as pd
import os
import shutil

def clean_temp():
    temp_file_list = os.listdir('temp')
    for f in temp_file_list:
        if f.split('.')[-1]=='docx':
            os.remove(f'temp/{f}')    


def create_word_docx(study_turn=1):

    df = pd.read_excel('temp/s02_words_record.xlsx')
    df = df.fillna('')
    df['first_word'] = [x[0] for x in df['word'].astype(str)]
    level_dict = dict(zip(df['study_turn'], df['level']))
    level = level_dict.get(study_turn)
    df = df[df['study_turn']<=study_turn]
    df = df.sort_values('word').reset_index(drop=True)

    word_list = df.to_dict(orient='records')
    print(len(word_list))


    temp_list = os.listdir('input/word模板')
    w_list = df['word'].tolist()
    for tep in temp_list:
        if tep[0]=='~':continue
        doc = DocxTemplate(f'input/word模板/{tep}')
        context = {'word_list': word_list, '_':'_______', 'b':'    ', 'all_w':' '.join(w_list)}
        doc.render(context)
        doc.save(f'temp/{level}{tep}')


def run():
    clean_temp()
    create_word_docx(study_turn=1)
    create_word_docx(study_turn=2)
    create_word_docx(study_turn=5)
if __name__ == '__main__':
    run()
